﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
// Krzysztof Heim
// pktools.codeplex.com

namespace PKTools
{
    public enum LogSeverity
    {
        Debug = 0,
        Info = 1,
        Warning = 2,
        Error = 3
    }

    public static class Log
    {
        public static readonly int
            Level;
        readonly static Dictionary<LogSeverity, char>
            severityCode = new Dictionary<LogSeverity, char>
            {
                { LogSeverity.Debug, 'D' },
                { LogSeverity.Info, 'I' },
                { LogSeverity.Warning, 'W' },
                { LogSeverity.Error, 'E' }
            };

        static Log()
        {
            Trace.AutoFlush = true;

            var
                appSettings = ConfigurationManager.AppSettings;

            Level = appSettings["Log.Level"].SafeToInt((int)LogSeverity.Debug);

            string
                file = appSettings["Log.File"];

            if (!string.IsNullOrEmpty(file))
                Trace.Listeners.Add(new LogTraceWriter(file));
        }

        public static void Entry(LogSeverity severity, string format, params object[] objs)
        {
            if (Level > (int)severity)
                return;

            Trace.WriteLine(DateTime.UtcNow.ToDetailString() + ' ' + severityCode[severity] + ": " + string.Format(format, objs));
        }
    }
}
